/*
 * @Author: anxia.ack anchenkai@come-future.com
 * @Date: 2025-04-13 20:17:12
 * @LastEditors: anxia.ack anchenkai@come-future.com
 * @LastEditTime: 2025-05-01 10:44:50
 * @FilePath: /free-learning-front/src/utils/request.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from "axios";
import type {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosResponse,
} from "axios";
import { ElMessage } from "element-plus";
import { AxiosHeaders } from "axios";
import { ResultEnum } from "@/enums/ResultEnum";
import { ACCESS_TOKEN_KEY, getToken, REFRESH_TOKEN_KEY } from "./auth";
import router from "@/router";
import { useUserStore } from "@/store";
// 创建 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // 从环境变量获取 API 基础 URL
  timeout: -1, // 请求超时时间
  headers: new AxiosHeaders({
    "Content-Type": "application/json;charset=utf-8",
  }),
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const accessToken = getToken();
    // 如果 Authorization 设置为 no-auth，则不携带 Token，用于登录、刷新 Token 等接口
    if (config.headers.Authorization !== "no-auth" && accessToken) {
      config.headers.Authorization = accessToken;
    } else {
      delete config.headers.Authorization;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    // 对响应数据做点什么

    const res = response.data;

    // 根据自定义错误码判断请求是否成功
    if (res.code === 200 || res.code === 0 || res.code === "00000") {
      // 成功返回数据
      return res.data;
    } else {
      // 处理业务错误
      console.log(111);
      
      ElMessage.error(res.message || "请求失败");
      return Promise.reject(new Error(res.message || "请求失败"));
    }
  },
  (error: any) => {
    const { config, response } = error;
    if (response) {
      const { code, msg } = response.data;
      if (code === ResultEnum.ACCESS_TOKEN_INVALID) {
        // Token 过期，刷新 Token
        localStorage.removeItem("userInfo");
        localStorage.removeItem(ACCESS_TOKEN_KEY);
        localStorage.removeItem(REFRESH_TOKEN_KEY);
        useUserStore().userInfo = {}
        router.push("/login");
        ElMessage.error({
          message: "登录状态已过期，请重新登录",
          grouping: true,
        });
      } else if (code === ResultEnum.REFRESH_TOKEN_INVALID) {
        return Promise.reject(new Error(msg || "Error"));
      } else if (code === ResultEnum.REPEAT_REQUEST) {
        return Promise.reject(new Error(msg || "Error"));
      } else {
        ElMessage.error(msg || "系统出错");
      }
    }
    return Promise.reject(error.message);
  }
);

// 封装 GET 请求
export function get<T>(url: string, params?: any, config?: any): Promise<T> {
  return service.get(url, { params, ...config });
}

// 封装 POST 请求
export function post<T>(url: string, data?: any, config?: any): Promise<T> {
  return service.post(url, data, config);
}

// 封装 PUT 请求
export function put<T>(url: string, data?: any, config?: any): Promise<T> {
  return service.put(url, data, config);
}

// 封装 DELETE 请求
export function del<T>(url: string, config?: any): Promise<T> {
  return service.delete(url, config);
}

// 导出 axios 实例
export default service;
